import { useState } from "react";
import { Button } from "./ui/button";
import { Card } from "./ui/card";
import { Badge } from "./ui/badge";
import {
  Dialog,
  DialogContent,
  DialogTrigger,
  DialogTitle,
  DialogDescription,
} from "./ui/dialog";

// 类型定义
export interface Agent {
  id: string;
  name: string;
  description: string;
  model?: string;
  system_prompt?: string;
  tools?: string[];
}

interface AgentManagerProps {
  agents: Agent[];
  selectedAgent: Agent | null;
  onAgentSelect: (agent: Agent) => void;
  onAgentCreate: (agent: Partial<Agent>) => Promise<void>;
  onAgentDelete: (id: string) => Promise<void>;
}

export function AgentManager({
  agents,
  onAgentSelect,
  onAgentCreate,
  onAgentDelete,
}: AgentManagerProps) {
  const [showAgentManager, setShowAgentManager] = useState(false);
  const [newAgent, setNewAgent] = useState<Partial<Agent>>({});

  const handleCreateAgent = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newAgent.name || !newAgent.description) return;

    try {
      await onAgentCreate(newAgent);
      setNewAgent({});
      setShowAgentManager(false);
    } catch (error) {
      console.error("Failed to create agent:", error);
    }
  };

  return (
    <Dialog open={showAgentManager} onOpenChange={setShowAgentManager}>
      <DialogTrigger asChild>
        <Button
          variant="outline"
          className="bg-gray-900/80 border-gray-600 hover:bg-gray-800"
        >
          <span className="mr-2">🤖</span>
          Agent 管理
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-4xl max-h-[80vh] bg-gray-900 border-gray-700 text-white">
        <DialogTitle>Agent 管理</DialogTitle>
        <DialogDescription>创建和管理 AI Agent</DialogDescription>

        <div className="flex h-[60vh] px-10 gap-6">
          {/* 左侧：Agent 列表 */}
          <div className="flex-1">
            <h3 className="text-lg font-semibold mb-4">现有 Agents</h3>
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {agents.map((agent) => (
                <Card
                  key={agent.id}
                  className="p-4 bg-gray-800 border-gray-600"
                >
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <h4 className="font-medium text-white">{agent.name}</h4>
                      <p className="text-sm text-gray-400 mt-1">
                        {agent.description}
                      </p>
                      {agent.model && (
                        <Badge className="mt-2 bg-blue-600">
                          {agent.model}
                        </Badge>
                      )}
                    </div>
                    <div className="flex gap-2">
                      <Button
                        variant="outline"
                        onClick={() => onAgentSelect(agent)}
                        className="text-xs px-2 py-1"
                      >
                        选择
                      </Button>
                      <Button
                        variant="destructive"
                        onClick={() => onAgentDelete(agent.id)}
                        className="text-xs px-2 py-1"
                      >
                        删除
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </div>

          {/* 右侧：创建新 Agent */}
          <div className="w-80">
            <h3 className="text-lg font-semibold mb-4">创建新 Agent</h3>
            <form onSubmit={handleCreateAgent} className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-2">名称</label>
                <input
                  type="text"
                  value={newAgent.name || ""}
                  onChange={(e) =>
                    setNewAgent((prev) => ({ ...prev, name: e.target.value }))
                  }
                  className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white"
                  placeholder="Agent 名称"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-2">描述</label>
                <textarea
                  value={newAgent.description || ""}
                  onChange={(e) =>
                    setNewAgent((prev) => ({
                      ...prev,
                      description: e.target.value,
                    }))
                  }
                  className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white h-20"
                  placeholder="Agent 描述"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-2">模型</label>
                <input
                  type="text"
                  value={newAgent.model || ""}
                  onChange={(e) =>
                    setNewAgent((prev) => ({ ...prev, model: e.target.value }))
                  }
                  className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white"
                  placeholder="gpt-4o-mini"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-2">
                  系统提示
                </label>
                <textarea
                  value={newAgent.system_prompt || ""}
                  onChange={(e) =>
                    setNewAgent((prev) => ({
                      ...prev,
                      system_prompt: e.target.value,
                    }))
                  }
                  className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white h-20"
                  placeholder="系统提示词"
                />
              </div>
              <Button type="submit" className="w-full">
                创建 Agent
              </Button>
            </form>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
